package net.loyin.app.model;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import net.loyin.ext.annotation.TableBind;
import net.loyin.app.model.base.BaseArticle;
import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * 文章
 */
@SuppressWarnings("serial")
@TableBind(tableName = Article.tableName)
public class Article extends BaseArticle<Article> {
	public static final String tableName="article";
	public static final Article dao = new Article();
	public Page<Article> pageQry(int pageNumber, int pageSize, String articleCateCode){
		if(StringUtils.isEmpty(articleCateCode)){
			articleCateCode="%%";
		}else{
			articleCateCode=articleCateCode+"%";
		}
		StringBuffer sql=new StringBuffer();
		sql.append(" from ");
		sql.append(Article.tableName);
		sql.append(" as a ,");
		sql.append(ArticleCate.tableName);
		sql.append(" as ac where a.cate_id=ac.id and ac.code like ? and ac.status=1 and a.status=1 order by a.create_datetime desc");
		return paginate(pageNumber,pageSize,"select a.id,a.title,a.summary,a.img,a.sup_title,a.create_datetime,ac.name cate_name ",sql.toString(),articleCateCode);
	}
	/**
	 * 更新阅读次数
	 * @param id
     */
	public void updateReadCount(String id) {
		Db.update("update article set read_count=read_count+1 where id=?",id);
	}
	public Article qryById(String id){
		return this.findFirst("select a.*,ac.name cate_name,ac.id cate_id,ac.code cate_code,acp.name pcate_name,acp.id pcate_id,acp.code pcate_code from "+tableName+" a left join "+ArticleCate.tableName+" ac on ac.id=a.cate_id left join "+ArticleCate.tableName+" acp on ac.parentid=acp.id where ac.status=1 and a.id=? ",id);
	}
	/**
	 * 根据分类码查询有限条数
	 * @param cateCode
	 * @param limit
     * @return
     */
	public List<Article> qryListByCateCode(String cateCode,int limit){
		StringBuffer sql=new StringBuffer("select a.*,ac.name cate_name,acp.name pcate_name from ");
		sql.append(tableName);
		sql.append(" a left join ");
		sql.append(ArticleCate.tableName);
		sql.append(" ac on ac.id=a.cate_id left join ");
		sql.append(ArticleCate.tableName);
		sql.append(" acp on ac.parentid=acp.id where ac.status=1 and ac.code like ? order by a.create_datetime desc limit ?");
		return this.find(sql.toString(),cateCode+"%", limit);
	}

	/**
	 * 查询固定数文章
	 * @param limit
	 * @return
     */
	public List<Article> qryList4Limit(int limit){
		StringBuffer sql=new StringBuffer("select a.*,ac.name cate_name,acp.name pcate_name from ");
		sql.append(tableName);
		sql.append(" a left join ");
		sql.append(ArticleCate.tableName);
		sql.append(" ac on ac.id=a.cate_id left join ");
		sql.append(ArticleCate.tableName);
		sql.append(" acp on ac.parentid=acp.id where ac.status=1 order by a.create_datetime desc limit ?");
		return this.find(sql.toString(),limit);
	}
}
